//
//  JUFNWebViewController.swift
//  WiBoPM
//
//  Created by 陈俊峰 on 2017/1/7.
//  Copyright © 2017年 陈俊峰. All rights reserved.
/**/

import UIKit
import SVProgressHUD

class JUFNWebViewController: UIViewController {
    
    var webView = UIWebView()
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
        requestData()
        // Do any additional setup after loading the view.
    }
    
    override func loadView() {
        view = webView
        webView.delegate = self;
    }
    // MARK:搭建界面
    private func setupUI() {
        view.backgroundColor = UIColor.white
        title = "登录"
        //设置左边按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: nil, title: "back", target: self, action: #selector(goback))
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: nil, title: "backDoor", target: self, action: #selector(gobackDoor))
    }
    @objc private func goback(){
        dismiss(animated: true, completion: nil)
    }
    @objc private func gobackDoor(){
        
        let jsString = "document.getElementById('userId').value = '952612837@qq.com',document.getElementById('passwd').value = 'cjf199011242jf'"
        webView.stringByEvaluatingJavaScript(from: jsString)
    }
    private func requestData(){
        
        let urlString:String = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        webView.loadRequest(URLRequest.init(url: URL.init(string: urlString)!))
    }
    
   
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //从这里的request,拿取URL,然后再截取所需要的code
        //http://www.itheima.com/?code=dee6a1832615d02f613f152a62912742)
        let urlString = request.url?.absoluteString
        let flag = "code="
        if (urlString?.contains(flag))! {
            let code = urlString?.components(separatedBy: flag).last
            JUFNAuthorViewModel.shared.loadRequest(code: code!, complete: { (success:Bool) in
                if success {
                    NotificationCenter.default.post(name: .ChangeRootViewController, object: "JUFNWelcomeVController")
                    
                }
            })
        }
        //发送网络请求,获取access数据
        return true
    }
    
    
    //    func loadRequest(code:String){
    //        let accessTokenStr = "https://api.weibo.com/oauth2/access_token"
    //        let prameters:[String:Any] = [
    //            "client_id":client_id,
    //            "client_secret":client_secret,
    //            "grant_type":"authorization_code",
    //            "code":code,
    //            "redirect_uri":redirect_uri
    //        ]
    //
    //
    //        JUFNetworkingTools.shared.request(method: .POST, urlString:accessTokenStr , prameters: prameters, finisnedClosure: { (resp:Any?, error:Error?) in
    //            if error == nil {
    //                let accessTokendict = resp as! [String:Any?]
    //
    //
    //                self.requestUserInfo(accessTokendict: accessTokendict)
    //            }
    //        })
    //
    //    }
    
    //    ///请求用户信息
    //    private func requestUserInfo(accessTokendict:[String:Any?]) {
    //        //创建一个模型,将字典转化为模型
    //
    //
    //        let userInfoPrameters = [
    //            "access_token":accessTokendict["access_token"],
    //            "uid":accessTokendict["uid"]
    //        ]
    //        let uesrInfoUrlString = "https://api.weibo.com/2/users/show.json"
    //        JUFNetworkingTools.shared.request(method: .GET, urlString: uesrInfoUrlString, prameters: userInfoPrameters, finisnedClosure: {(resp:Any?,error:Error?) -> () in
    //            //将accessToken数据字典和请求到的userInfo合并到一个模型中去
    //            if error == nil {
    //                var userInfoDict = resp as! [String:Any?]
    //                for (key,value) in accessTokendict{
    //                   userInfoDict[key] = value
    //                }
    //                let account = JUFNUserAccount(dict: userInfoDict)
    //                NSKeyedArchiver.archiveRootObject(account, toFile: documentPath)
    //                
    //                
    //                print(userInfoDict)
    //            }
    //        })
    //    }
    //    
    
}

extension JUFNWebViewController:UIWebViewDelegate{
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show(withStatus: "正在加载中,请稍等")
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
}
